from flask import Blueprint, render_template, jsonify\
    , flash, request, make_response, redirect, url_for
from App.models import User, ScenicSpot, Comment
from App.ext import db

blue = Blueprint('blue', __name__)


def init_view(app):
    app.register_blueprint(blueprint=blue)


@blue.route('/')
def index():
    db.create_all()
    return render_template('index.html')


@blue.route('/backstage')
def backstage():
    return render_template('backstage.html')


@blue.route('/elz')
def elzindex():
    """首页展示数据"""
    scenics = ScenicSpot.query.all()
    count = len(scenics)
    sc = []
    page = int(request.args.get('page'))
    limit = int(request.args.get('limit'))
    for scenic in scenics:
        s_json = scenic.__dict__
        del s_json['_sa_instance_state']
        sc.append(s_json)
    dic = {"code": 0, "msg": "", "count": count, 'data': sc[(page-1)*limit: (page-1)*limit+limit]}
    return make_response(jsonify(dic))


@blue.route('/add', methods=['POST'])
def add():
    """添加"""
    s = ScenicSpot()
    dic = request.form.to_dict()
    # 提取指定的列
    s_ids = ScenicSpot.query.with_entities(ScenicSpot.s_id)
    if dic['s_id'] in s_ids:
        return flash('已存在，添加失败')

    s.s_id = dic['s_id']
    s.s_name = dic['s_name']
    s.s_level = dic['s_level']
    s.s_area = dic['s_area']
    s.s_PV = 0
    s.s_LN = 0
    img = request.files.get('img')
    img.save(rf'App\static\images\{str(s.s_id)}.jpg')
    s.s_path = f'../static/images/{str(s.s_id)}.jpg'
    s.s_detail = dic['s_detail']
    db.session.add(s)
    db.session.commit()
    flash('添加成功')
    return render_template('backstage.html')


@blue.route('/modify', methods=['POST'])
def modify():
    """修改"""
    dic = request.form.to_dict()
    print(dic)
    img = request.files.get('img')
    img.save(rf'App\static\images\{str(dic["s_id"])}.jpg')
    (ScenicSpot.query.filter_by(s_id=dic['s_id'])
     .update({'s_name': dic['s_name'],
              's_level': dic['s_level'],
              's_area': dic['s_area'],
              # 's_PV': dic['s_PV'],
              # 's_LN': dic['s_LN'],
              #  's_path': dic['s_path'],
              's_detail': dic['s_detail']
              }))
    db.session.commit()
    return render_template('backstage.html')


@blue.route('/detail/', methods=['POST', 'GET'])
def detail():
    """根据id查询,详情信息页面"""
    s_id = request.args.get('s_id')
    s = ScenicSpot.query.filter_by(s_id=s_id).first()
    s.s_PV += 1
    db.session.commit()
    return render_template("details.html"
                           , s_id=s.s_id
                           , s_name=s.s_name
                           , s_level=s.s_level
                           , s_area=s.s_area
                           , s_PV=s.s_PV
                           , s_LN=s.s_LN
                           , s_path=s.s_path
                           , s_detail=s.s_detail
                           )


@blue.route('/delete', methods=['POST', 'GET'])
def delete():
    """根据id删除"""
    s_id = int(request.args.get('s_id'))
    s = ScenicSpot.query.filter_by(s_id=s_id).first()
    db.session.delete(s)
    db.session.commit()
    return render_template('details.html')


@blue.route('/dianzan')
def dianzai():
    s_id = int(request.args.get('s_id'))
    s = ScenicSpot.query.filter_by(s_id=s_id).first()
    s.s_LN += 1

    db.session.commit()
    return render_template('details.html')


@blue.route('/addpl')
def addpl():
    s_id = int(request.args.get('s_id'))
    c_comment = int(request.args.get('c_comment'))

    c = Comment()
    c.s_id = s_id
    c.c_comment = c_comment
    db.session.add(c)
    db.session.commit()
    return render_template('details.html')


@blue.route('/pl')
def pl():
    s_id = int(request.args.get('s_id'))
    scenics = Comment.query.filter_by(s_id=s_id).with_entities(Comment.c_comment)
    sc = []
    for scenic in scenics:
        # s_json = scenic.__dict__
        # del s_json['_sa_instance_state']
        sc.append(scenic[0])
    return make_response(jsonify(sc))
